<script setup>
import bus from "../../utils/eventBus"
import AnswerMe from "pages/answer-com/answer-me.vue";
import AnswerRobot from "pages/answer-com/answer-robot.vue";
import AnswerRobotMaterial from "pages/answer-com/answer-robot-material.vue";
import AnswerMeFile from "pages/answer-com/answer-me-file.vue";
import AnswerRobotPoint from "pages/answer-com/answer-robot-point.vue";
import AnswerWelcome from "pages/component/answerWelcome.vue";
import {reactive} from "vue";
import AnswerEventAll from "pages/answer-com/answer-event-all.vue";
import AnswerEventGuide from "pages/answer-com/answer-event-guide.vue";
import AnswerEventSituation from "pages/answer-com/answer-event-situation.vue";
import {conf} from "src/utils/serverHost.js";
import AnswerRobotText from "pages/answer-com/answer-robot-text.vue";

let prop = defineProps(['showDown'])
let str = '';
let strIndex = 0;
let contentIndex = 0;
let ws = new WebSocket("ws://112.192.23.17:5080/ws");
// let ws = new WebSocket("ws://192.168.31.7:5080/ws");
let fileUrl = '';
let allQa = reactive({
    activeEventId: '',
    activeEventName: '',
    list: [{}]
})
ws.onopen = function (res) {
    //todo
}
ws.onclose = function (res) {
    ws = null;
}
ws.onmessage = function (res) {
    getMsg(res.data);
}
ws.onerror = function (res) {
    console.log(res.data);
}
const moveScroll = () => {
    setTimeout(() => {
        let divElement = document.getElementById('answer');
        if (!divElement) return
        divElement.scrollTo({
            top: divElement.scrollHeight,
            behavior: "smooth" // 可选：平滑滚动
        });
        prop.showDown = false;
    }, 100)
}
const getMsg = (res) => {
    moveScroll()
    try {
        res = JSON.parse(res);
    } catch (e) {
        //todo
    }
    if (res.type == 'displaystream') {
        if (res.content == "\n") return; //后台返回有错误数据
        if (res.content.content == 'finish') {
            allQa.list[allQa.list.length - 1].msg.text.push({
                textType: '',
                content: [],
            })
            strIndex++;
            str = '';
            contentIndex = 0;
            return
        }
        if (res.content.messagetype == 'mistakefile') {
            let arr = res.content.content.split('^^')
            res.content.content = arr[0];
            fileUrl = arr[1]?.replace('\n', '');
        }
        for (let x of res.content.content) {
            let strIndexVal = allQa.list[allQa.list.length - 1].msg.text[strIndex];
            str += res.content.style == 'title' ? `<strong style="font-size: 16px">${x}</strong>` : `<span onclick="window.clickEvent(this,'${res.content?.messagetype}','${fileUrl}')">${x}</span>`; //需要加粗的\
            if (!strIndexVal['content'][contentIndex]?.con) strIndexVal['content'][contentIndex] = {
                con: '',
                typewriter: '',
            };
            strIndexVal['content'][contentIndex]['con'] = str;
            strIndexVal['content'][contentIndex]['typewriter'] = res.content.typewriter;
            strIndexVal['content'][contentIndex]['isTit'] = res.content.style;
            strIndexVal['textType'] = res.content.messagetype;
            if (res.content.typewriter == 'row' && (str.replace(/<[^>]+>/g, '')).length > 30) {
                str = '';
            }
            if (x == '\n') {
                if ((res.content.messagetype == 'guess' || res.content.messagetype == 'kgevent')&&res.content.style != 'title') {
                    strIndexVal['content'][contentIndex]['con'] += '>'
                }
                hideTypewriterRow()
                contentIndex++;
                str = ''
            }
        }
    }
}
const hideTypewriterRow = () => {
    let nodes = allQa.list[allQa.list.length - 1].msg.text;
    nodes.forEach(x => {
        x.content.forEach(y => {
            if (y.typewriter == 'row') y['hideRow'] = true;
        })
    });
}
bus.$on('sendQuestion', (data) => {
    let sendMsg = window.fromNetwork?`yes^^${data}`:`no^^${data}`;
    ws.send(sendMsg);
    strIndex = 0;
    contentIndex = 0;
    allQa.list.push({
        who: 'me',
        type: 'meText',
        msg: data,
    })
    allQa.list.push({
        who: 'ro',
        type: 'roText',
        msg: {
            text: [{
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }],
        },
    })
})
bus.$on('selectType', (data) => {
    ws.send(data);
})
bus.$on('clickEvent', (eventName, eventId) => {
    allQa.activeEventId = eventId;
    allQa.activeEventName = eventName;
    // strIndex = 0;
    // contentIndex = 0;
    // str = '';
    // let sendMsg = window.fromNetwork?`yes^^什么是${eventName}`:`no^^什么是${eventName}`;
    // sendMsg = window.explain?`yes^^${eventName}`:`no^^${eventName}`;
    // ws.send(sendMsg);
    allQa.list.push({
        who: 'me',
        type: 'meText',
        msg: '您选择的事项：' + eventName,
    })
    allQa.list.push({
        who: 'ro',
        type: 'eventAll',
      msg: {
          eventName:eventName,
      },
    })
    moveScroll()
})
bus.$on('clickEventGuide', (eventName) => {
    fetch(conf.httpHost + '/QueryEventElementByEventId?eventId=' + allQa.activeEventId, {
        method: 'GET',
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
    }).then(data => {
        data = JSON.parse(data);
        allQa.list.push({
            who: 'me',
            type: 'meText',
            msg: allQa.activeEventName + '的事项指南',
        })
        allQa.list.push({
            who: 'ro',
            type: 'eventGuide',
            msg: data.eventelement,
        })
        moveScroll()
    })
})
bus.$on('clickEventSituation', () => {
    fetch(conf.httpHost + '/QueryEventQxByEventid?eventId=' + allQa.activeEventId, {
        method: 'GET',
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
    }).then(data => {
        console.log(data); // 服务器返回的响应数据
        data = JSON.parse(data);
        allQa.list.push({
            who: 'me',
            type: 'meText',
            msg: allQa.activeEventName + '的事项情形',
        })
        allQa.list.push({
            who: 'ro',
            type: 'eventSituation',
            eventName: allQa.activeEventName,
            msg: data.eventelement,
        })
        moveScroll()
    })
})
bus.$on('clickEventMaterial', () => {
    fetch(conf.httpHost + '/QueryEventMaterialByEventId?eventId=' + allQa.activeEventId, {
        method: 'GET',
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
    }).then(data => {
        data = JSON.parse(data);
        allQa.list.push({
            who: 'me',
            type: 'meText',
            msg: allQa.activeEventName + '的事项材料',
        })
        allQa.list.push({
            who: 'ro',
            type: 'eventMaterial',
            eventName: allQa.activeEventName,
            msg: data.eventmaterial,
        })
        moveScroll()
    })
})
//选择情形项
bus.$on('clickSituationItem', (qxcode) => {
    fetch(conf.httpHost + `/QueryEventQxMaterialByEventidAndQxcode?eventId=${allQa.activeEventId}&eventQxCode=${qxcode}`, {
        method: 'GET',
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
    }).then(data => {
        data = JSON.parse(data)
        allQa.list.push({
            who: 'me',
            type: 'meText',
            msg: allQa.activeEventName + '所需的材料：',
        })
        allQa.list.push({
            who: 'ro',
            eventName: allQa.activeEventName,
            type: 'eventMaterial',
            msg: data.eventelement,
        })
        moveScroll()
    })
})
bus.$on('uploadFile', (data) => {
    strIndex = 0;
    contentIndex = 0;
    str = '';
    allQa.list.push({
        who: 'me',
        type: 'meFile',
        msg: data,
    })
    allQa.list.push({
        who: 'ro',
        type: 'roText',
        msg: {
            text: [{
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }, {
                textType: '',
                content: [],
            }],
        },
    })
    moveScroll();
})
</script>

<template>
    <div class="answer-dom" id="answer">
        <answer-welcome></answer-welcome>
        <div v-for="x in allQa.list">
            <answer-me v-if="x.type == 'meText'" :msg="x.msg"></answer-me>
            <answer-robot v-if="x.type == 'roText'" :msg="x.msg"></answer-robot>
            <answer-event-all v-if="x.type == 'eventAll'" :msg="x.msg"></answer-event-all>
            <answer-event-guide v-if="x.type == 'eventGuide'" :eventName="x.eventName"
                                :msg="x.msg"></answer-event-guide>
            <answer-event-situation v-if="x.type == 'eventSituation'" :eventName="x.eventName"
                                    :msg="x.msg"></answer-event-situation>
            <answer-robot-material v-if="x.type == 'eventMaterial'" :eventName="x.eventName"
                                   :msg="x.msg"></answer-robot-material>
            <answer-me-file v-if="x.type == 'meFile'" :msg="x.msg"></answer-me-file>
            <answer-robot-text v-if="x.type == 'roRes'" :msg="x.msg"></answer-robot-text>
        </div>

        <!--        <answer-me></answer-me>-->
        <!--        <answer-robot-material></answer-robot-material>-->
        <!--        <answer-robot-point></answer-robot-point>-->
    </div>
</template>

<style scoped lang="scss">
.answer-dom {
    padding: 20px 0;
    height: calc(100vh - 212px);
    overflow-y: auto;
}
</style>
